import 'package:flutter/foundation.dart';
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
import 'package:uuid/uuid.dart';

class UUIDManager {
  // 单例模式，确保UUIDManager实例唯一
  static final UUIDManager _instance = UUIDManager._internal();
  factory UUIDManager.shared() => _instance;

  // 内部构造函数
  UUIDManager._internal();

  // 创建一个Flutter Secure Storage实例，用于跨平台安全存储UUID
  final FlutterSecureStorage _storage = const FlutterSecureStorage();
  final String _uuidKey = 'device_uuid'; // 存储UUID的键
  final Uuid _uuidGenerator = Uuid(); // UUID生成器

  // 获取UUID的公共方法，返回一个Future<String>类型
  Future<String> getUUID() async {
    try {
      // 1. 尝试从安全存储中读取UUID
      String? storedUuid = await _storage.read(key: _uuidKey);
      // 2. 如果没有存储UUID，则生成一个新的UUID并存储起来
      storedUuid ??= await _generateAndStoreUUID();
      return storedUuid;
    } catch (e) {
      // 处理可能的异常（如存储读取失败），记录异常并重新生成UUID
      debugPrint("Error retrieving UUID: $e");
      return _generateAndStoreUUID();
    }
  }

  /// 生成新的UUID并保存到安全存储中
  /// [result] 异步返回生成的UUID
  /// [_generateAndStoreUUID] 私有方法，用于生成新的UUID并保存到安全存储中
  Future<String> _generateAndStoreUUID() async {
    final String newUuid = _uuidGenerator.v4(); // 使用UUID库生成一个新的UUID
    await _storage.write(key: _uuidKey, value: newUuid); // 将生成的UUID写入安全存储
    return newUuid; // 返回生成的UUID
  }
}
